package core;

import desktop_fields.Field;
import desktop_resources.GUI;

public class Game {

	private GameBoard gb = new GameBoard();
	private Player[] players;
	private int playersLeft;
	
	
	public Game(){
		Field[] convField = gb.getFieldsGUI();
		GUI.create(convField);
	}
	
	private void startNewGame(){
		int numberOfPlayers;
		GUI.getUserButtonPressed("New Game", "Start!");
		numberOfPlayers = GUI.getUserInteger("How many players? (Between 2 and 6)", 2, 6);
		players = new Player[numberOfPlayers];
		for(int i =0; i<players.length; i++){
			players[i] = new Player();
		}
		playersLeft = numberOfPlayers;
		for(Player p : players){
			String temp = GUI.getUserString("Write your name (Two players cant have the same name)");
			p.setName(temp);
			GUI.addPlayer(p.getName(), 30000);
			GUI.setCar(1, p.getName());
		}
		
	}
	
	private void updateBalance(){
		for(Player pl : players){
			GUI.setBalance(pl.getName(), pl.getPoints());
		}
	}
	
	private void playTurn(Player p){
		GUI.getUserButtonPressed("Start your turn " + p.getName(), "RollzRoyze");
		p.throwDice();
		p.setPosition(p.getDice());
		GUI.setDice(p.getDice()[0].getValue(), p.getDice()[1].getValue());
		GUI.removeAllCars(p.getName());
		GUI.setCar(p.getPosition()+1, p.getName());
		gb.getFields()[p.getPosition()].landOnField(p);
		
		if(gb.getFields()[p.getPosition()].getOwner() !=null && gb.getFields()[p.getPosition()].getOwner() == p){
			GUI.setOwner(p.getPosition()+1, p.getName());
		}
		if(p.getLost()){
			GUI.removeAllCars(p.getName());
			for(int i = 0; i< p.returnFields().length; i++){
				GUI.removeOwner(gb.getIndexOf(p.returnFields()[i].getName())+1);
			}
			playersLeft--;
			p.removeOwnedFields();
		}
		
		updateBalance();
		
	}
	
	private void endTurn(){
		GUI.getUserButtonPressed("End your Turn", "End turn");
		
	}
	
	public void playGame(){
		startNewGame();
		while(playersLeft>1){
			for(Player p : players){
				if(!p.getLost()){
					playTurn(p);
					endTurn();
				}
			}
		}
		GUI.displayChanceCard("Player " + getLuckyPlayer() + " have won");		
	}
	private String getLuckyPlayer(){
		String temp = "";
		for(Player p : players){
			if(!p.getLost())
				temp = p.getName();
		}
		return temp;
	}
	
	
	
}
